package myview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bigchun.seeland.R;


/**
 * Created by fei on 2018/1/3.
 */

public class PullLoadMoreRecyclerView extends LinearLayout {
    private RecycleViewEx mRecyclerView;
    private SwipeRefreshLayoutEx mSwipeRefreshLayout;
    private PullLoadMoreListener mPullLoadMoreListener;
    private boolean hasMore = true;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;
    private boolean pullRefreshEnable = true;
    private boolean pushRefreshEnable = true;
    private Context mContext;
//    private TextView loadMoreText;
//    public LinearLayout loadMoreLayout;
    private EmptyAdapterDataObserver mEmptyDataObserver;

    public PullLoadMoreRecyclerView(Context context) {
        super(context);
        initView(context);
    }

    public PullLoadMoreRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.pull_loadmore_layout, null);
        mSwipeRefreshLayout = (SwipeRefreshLayoutEx) view.findViewById(R.id.swipeRefreshLayout);
        try {
            mSwipeRefreshLayout.setDistanceToTriggerSync(300);
        }catch (Exception e){

        }
        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_green_dark, android.R.color.holo_blue_dark, android.R.color.holo_orange_dark);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayoutOnRefresh(this));

        mRecyclerView = (RecycleViewEx) view.findViewById( R.id.recycler_view);
        mRecyclerView.setVerticalScrollBarEnabled(true);

        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addOnScrollListener(new RecyclerViewOnScroll(this));
        mRecyclerView.setOnTouchListener(new onTouchRecyclerView());
//        loadMoreLayout = (LinearLayout) view.findViewById(R.id.loadMoreLayout);
//        loadMoreText = (TextView) view.findViewById(R.id.loadMoreText);
        this.addView(view);

    }


    /**
     * LinearLayoutManager
     */
    public void setLinearLayout() {
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
//        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        linearLayoutManager.setSmoothScrollbarEnabled(true);
//        linearLayoutManager.setAutoMeasureEnabled(true);
//        mRecyclerView.setLayoutManager(linearLayoutManager);

        AdvertiseLinearLayoutManager linearLayoutManager = new AdvertiseLinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);
        mRecyclerView.setLayoutManager(linearLayoutManager);


    }

    /**
     * GridLayoutManager
     */

    public void setGridLayout(int spanCount) {

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, spanCount);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(gridLayoutManager);
    }
    public void setGridLayout2(int spanCount) {

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, spanCount);


        //通过isTitle的标志来判断是否是title
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
//                MyLog.e("show",position+"toshitringxxxxx888");
                if(position ==0){
                    return 2;
                }else {
                    return 1;
                }
            }
        });
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(gridLayoutManager);
    }


    /**
     * StaggeredGridLayoutManager
     */

    public void setStaggeredGridLayout(int spanCount) {
        StaggeredGridLayoutManager staggeredGridLayoutManager =
                new StaggeredGridLayoutManager(spanCount, LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(staggeredGridLayoutManager);
    }
    public void cancleAnimal() {
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    public RecyclerView.LayoutManager getLayoutManager() {
        return mRecyclerView.getLayoutManager();
    }
    public GridLayoutManager getGridLayoutManager() {
        return (GridLayoutManager) mRecyclerView.getLayoutManager();
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public void setItemAnimator(RecyclerView.ItemAnimator animator) {
        mRecyclerView.setItemAnimator(animator);
    }

    public void addItemDecoration(RecyclerView.ItemDecoration decor, int index) {
        mRecyclerView.addItemDecoration(decor, index);
    }

    public void addItemDecoration(RecyclerView.ItemDecoration decor) {
        mRecyclerView.addItemDecoration(decor);
    }

    public void scrollToTop() {
        mRecyclerView.scrollToPosition(0);
    }
    public void smoothScrollToPosition() {
        mRecyclerView.getLayoutManager().smoothScrollToPosition(mRecyclerView,null,5);
//        mRecyclerView.smoothScrollToPosition(0);
    }
    public void smoothScrollToPositionitem(int position) {
        mRecyclerView.getLayoutManager().smoothScrollToPosition(mRecyclerView,null,position);
    }


    public void scrollToPositionWithOffset1() {
//        mRecyclerView.getLayoutManager().scrollto
    }


    public void setAdapter(RecyclerView.Adapter adapter) {
        if (mEmptyDataObserver == null) {
            mEmptyDataObserver = new EmptyAdapterDataObserver();
        }
        RecyclerView.Adapter oldAdapter = mRecyclerView.getAdapter();
        if (oldAdapter != null) {
            oldAdapter.unregisterAdapterDataObserver(mEmptyDataObserver);
        }
        if (adapter != null) {
            mRecyclerView.setAdapter(adapter);
            adapter.registerAdapterDataObserver(mEmptyDataObserver);
        }
    }

    /**
     * When view detached from window , unregister adapter data observer, avoid momery leak.
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        RecyclerView.Adapter oldAdapter = mRecyclerView.getAdapter();
        if (oldAdapter != null) {
            oldAdapter.unregisterAdapterDataObserver(mEmptyDataObserver);
        }
    }

    /**
     * This Observer receives adapter data change.
     * When adapter's item count greater than 0 and empty view has been set,then show the empty view.
     * when adapter's item count is 0 ,then empty view hide.
     */
    private class EmptyAdapterDataObserver extends RecyclerView.AdapterDataObserver {
        @Override
        public void onChanged() {

        }
    }


    public void setPullRefreshEnable(boolean enable) {
        pullRefreshEnable = enable;
        setSwipeRefreshEnable(enable);
    }

    public boolean getPullRefreshEnable() {
        return pullRefreshEnable;
    }

    public void setSwipeRefreshEnable(boolean enable) {
        mSwipeRefreshLayout.setEnabled(enable);
    }

    public boolean getSwipeRefreshEnable() {
        return mSwipeRefreshLayout.isEnabled();
    }


    public void setColorSchemeResources(int... colorResIds) {
        mSwipeRefreshLayout.setColorSchemeResources(colorResIds);

    }

    public SwipeRefreshLayout getSwipeRefreshLayout() {
        return mSwipeRefreshLayout;
    }

    public void setRefreshing(final boolean isRefreshing) {
        mSwipeRefreshLayout.post(new Runnable() {

            @Override
            public void run() {
                if (pullRefreshEnable)
                    mSwipeRefreshLayout.setRefreshing(isRefreshing);
            }
        });

    }


    /**
     * Solve IndexOutOfBoundsException exception
     */
    public class onTouchRecyclerView implements OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return isRefresh || isLoadMore;
        }
    }


    public boolean getPushRefreshEnable() {
        return pushRefreshEnable;
    }

    public void setPushRefreshEnable(boolean pushRefreshEnable) {
        this.pushRefreshEnable = pushRefreshEnable;
    }

//    public LinearLayout getFooterViewLayout() {
//        return loadMoreLayout;
//    }
//
//    public void setFooterViewBackgroundColor(int color) {
//        loadMoreLayout.setBackgroundColor(ContextCompat.getColor(mContext, color));
//    }
//
//    public void setFooterViewText(CharSequence text) {
//        loadMoreText.setText(text);
//    }
//
//    public void setFooterViewText(int resid) {
//        loadMoreText.setText(resid);
//    }
//
//    public void setFooterViewTextColor(int color) {
//        loadMoreText.setTextColor(ContextCompat.getColor(mContext, color));
//    }


    public void refresh() {
        if (mPullLoadMoreListener != null) {
            mPullLoadMoreListener.onRefresh();
        }
    }

    public void loadMore() {
        if (mPullLoadMoreListener != null && hasMore) {
            invalidate();
            mPullLoadMoreListener.onLoadMore();

        }
    }
    public void onScrollChanged(int heightTotal) {
            mPullLoadMoreListener.onScrollChanged(heightTotal);
    }
    public void onScrollState(int type) {
        mPullLoadMoreListener.onScrollState(type);
    }


    public void setPullLoadMoreCompleted() {
        isRefresh = false;
        setRefreshing(false);
        isLoadMore = false;
    }


    public void setOnPullLoadMoreListener(PullLoadMoreListener listener) {
        mPullLoadMoreListener = listener;
    }


    public boolean isLoadMore() {
        return isLoadMore;
    }

    public void setIsLoadMore(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
    }

    public boolean isRefresh() {
        return isRefresh;
    }

    public void setIsRefresh(boolean isRefresh) {
        this.isRefresh = isRefresh;
    }

    public boolean isHasMore() {
        return hasMore;
    }

    public void setHasMore(boolean hasMore) {
        this.hasMore = hasMore;
    }

    public interface PullLoadMoreListener {
        void onRefresh();

        void onLoadMore();

        void onScrollChanged(int heightTotal);

        void onScrollState(int type);
    }

}

